package com.rpc.core.codec.impl.json;

import com.rpc.core.codec.RpcCodec;
import com.rpc.core.util.GsonUtil;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.json.JsonObjectDecoder;

public class JsonCodec extends JsonObjectDecoder implements RpcCodec {

    @Override
    public <T> void serialize(T obj, ByteBuf byteBuf) {

        String objString = GsonUtil.GsonString(obj);
        byte[] bytes = objString.getBytes();
        byteBuf.writeBytes(bytes, 0, bytes.length);

    }

    @Override
    public <T> Object deserialize(ByteBuf byteBuf) {

        byte[] array = byteBuf.array();
        try {
            return GsonUtil.deserialize(array);
        } catch (Exception e) {
            throw new RuntimeException("json deserialize exception!");
        }

    }
}
